import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  Tabs,
  Tab,
  TextField,
  Switch,
  FormControlLabel,
  Button,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Divider,
  Alert,
  Slider,
  Grid,
  Card,
  CardContent,

  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,

  Chip,
} from '@mui/material';
import {
  Save as SaveIcon,
  Restore as RestoreIcon,

  FileDownload as ImportIcon,
  FileUpload as ExportIcon,
  Security as SecurityIcon,
  Palette as PaletteIcon,
  Terminal as TerminalIcon,
  Settings as SettingsIcon,
  Info as InfoIcon,
} from '@mui/icons-material';
import { invoke } from '@tauri-apps/api/core';
import { open, save } from '@tauri-apps/plugin-dialog';
import { readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';
import toast from 'react-hot-toast';

// Store
import { useAppStore } from '../store/appStore';

// Types
import type { AppConfig } from '../types/config';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`settings-tabpanel-${index}`}
      aria-labelledby={`settings-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

const Settings: React.FC = () => {
  const { config, setConfig, connections } = useAppStore();
  const [currentTab, setCurrentTab] = useState(0);
  const [localConfig, setLocalConfig] = useState<AppConfig | null>(null);
  const [hasChanges, setHasChanges] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [showResetDialog, setShowResetDialog] = useState(false);


  // 初始化本地配置
  useEffect(() => {
    if (config) {
      setLocalConfig({ ...config });
    }
  }, [config]);

  // 检查是否有未保存的更改
  useEffect(() => {
    if (config && localConfig) {
      setHasChanges(JSON.stringify(config) !== JSON.stringify(localConfig));
    }
  }, [config, localConfig]);

  // 更新本地配置
  const updateLocalConfig = (updates: Partial<AppConfig>) => {
    if (localConfig) {
      setLocalConfig({ ...localConfig, ...updates });
    }
  };

  // 保存配置
  const saveConfig = async () => {
    if (!localConfig) return;

    setIsLoading(true);
    try {
      await invoke('save_config', { config: localConfig });
      setConfig(localConfig);
      setHasChanges(false);
      toast.success('配置已保存');
    } catch (error) {
      console.error('Failed to save config:', error);
      toast.error('保存配置失败: ' + (error as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  // 重置配置
  const resetConfig = async () => {
    setIsLoading(true);
    try {
      const defaultConfig = await invoke('get_default_config') as AppConfig;
      setLocalConfig(defaultConfig);
      setShowResetDialog(false);
      toast.success('配置已重置为默认值');
    } catch (error) {
      console.error('Failed to reset config:', error);
      toast.error('重置配置失败: ' + (error as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  // 导出配置
  const exportConfig = async () => {
    try {
      const filePath = await save({
        title: '导出配置',
        defaultPath: 'tabby-config.json',
        filters: [{
          name: 'JSON',
          extensions: ['json']
        }]
      });

      if (filePath) {
        const exportData = {
          config: localConfig,
          connections: connections,
          exportedAt: new Date().toISOString(),
          version: localConfig?.app_version || '1.0.0',
        };

        await writeTextFile(filePath, JSON.stringify(exportData, null, 2));
        toast.success('配置已导出');
      }
    } catch (error) {
      console.error('Failed to export config:', error);
      toast.error('导出配置失败: ' + (error as Error).message);
    }
  };

  // 导入配置
  const importConfig = async () => {
    try {
      const filePath = await open({
        title: '导入配置',
        filters: [{
          name: 'JSON',
          extensions: ['json']
        }]
      });

      if (filePath && typeof filePath === 'string') {
        const content = await readTextFile(filePath);
        const importData = JSON.parse(content);

        if (importData.config) {
          setLocalConfig(importData.config);
          toast.success('配置已导入');
        } else {
          toast.error('无效的配置文件格式');
        }
      }
    } catch (error) {
      console.error('Failed to import config:', error);
      toast.error('导入配置失败: ' + (error as Error).message);
    }
  };

  if (!localConfig) {
    return (
      <Box sx={{ p: 3, textAlign: 'center' }}>
        <Typography>加载配置中...</Typography>
      </Box>
    );
  }

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 设置头部 */}
      <Paper sx={{ mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', p: 2 }}>
          <Typography variant="h5">
            应用设置
          </Typography>
          
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={<ImportIcon />}
              onClick={importConfig}
            >
              导入
            </Button>
            <Button
              variant="outlined"
              startIcon={<ExportIcon />}
              onClick={exportConfig}
            >
              导出
            </Button>
            <Button
              variant="outlined"
              startIcon={<RestoreIcon />}
              onClick={() => setShowResetDialog(true)}
            >
              重置
            </Button>
            <Button
              variant="contained"
              startIcon={<SaveIcon />}
              onClick={saveConfig}
              disabled={!hasChanges || isLoading}
            >
              保存
            </Button>
          </Box>
        </Box>

        {hasChanges && (
          <Alert severity="info" sx={{ mx: 2, mb: 2 }}>
            您有未保存的更改，请记得保存配置。
          </Alert>
        )}

        <Tabs
          value={currentTab}
          onChange={(_, newValue) => setCurrentTab(newValue)}
          sx={{ borderTop: 1, borderColor: 'divider' }}
        >
          <Tab icon={<SettingsIcon />} label="常规" />
          <Tab icon={<PaletteIcon />} label="主题" />
          <Tab icon={<TerminalIcon />} label="终端" />
          <Tab icon={<SecurityIcon />} label="安全" />
          <Tab icon={<InfoIcon />} label="关于" />
        </Tabs>
      </Paper>

      {/* 设置内容 */}
      <Box sx={{ flex: 1, overflow: 'auto' }}>
        {/* 常规设置 */}
        <TabPanel value={currentTab} index={0}>
          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    应用设置
                  </Typography>
                  
                  <FormControl fullWidth sx={{ mb: 2 }}>
                    <InputLabel>日志级别</InputLabel>
                    <Select
                      value={localConfig.log_level}
                      label="日志级别"
                      onChange={(e) => updateLocalConfig({ log_level: e.target.value as any })}
                    >
                      <MenuItem value="error">错误</MenuItem>
                      <MenuItem value="warn">警告</MenuItem>
                      <MenuItem value="info">信息</MenuItem>
                      <MenuItem value="debug">调试</MenuItem>
                      <MenuItem value="trace">跟踪</MenuItem>
                    </Select>
                  </FormControl>

                  <FormControlLabel
                    control={
                      <Switch
                        checked={localConfig.auto_save_config}
                        onChange={(e) => updateLocalConfig({ auto_save_config: e.target.checked })}
                      />
                    }
                    label="自动保存配置"
                  />
                </CardContent>
              </Card>
            </Grid>

            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    窗口设置
                  </Typography>
                  
                  <TextField
                    fullWidth
                    label="默认宽度"
                    type="number"
                    value={localConfig.window?.default_width || 1200}
                    onChange={(e) => updateLocalConfig({
                      window: {
                        ...localConfig.window,
                        default_width: parseInt(e.target.value) || 1200
                      }
                    })}
                    sx={{ mb: 2 }}
                  />
                  
                  <TextField
                    fullWidth
                    label="默认高度"
                    type="number"
                    value={localConfig.window?.default_height || 800}
                    onChange={(e) => updateLocalConfig({
                      window: {
                        ...localConfig.window,
                        default_height: parseInt(e.target.value) || 800
                      }
                    })}
                    sx={{ mb: 2 }}
                  />

                  <FormControlLabel
                    control={
                      <Switch
                        checked={localConfig.window?.remember_size || false}
                        onChange={(e) => updateLocalConfig({
                          window: {
                            ...localConfig.window,
                            remember_size: e.target.checked
                          }
                        })}
                      />
                    }
                    label="记住窗口大小"
                  />
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </TabPanel>

        {/* 主题设置 */}
        <TabPanel value={currentTab} index={1}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                主题配置
              </Typography>
              
              <FormControl fullWidth sx={{ mb: 2 }}>
                <InputLabel>主题模式</InputLabel>
                <Select
                  value={localConfig.theme?.mode || 'dark'}
                  label="主题模式"
                  onChange={(e) => updateLocalConfig({
                    theme: {
                      ...localConfig.theme,
                      mode: e.target.value as any
                    }
                  })}
                >
                  <MenuItem value="light">浅色</MenuItem>
                  <MenuItem value="dark">深色</MenuItem>
                  <MenuItem value="auto">跟随系统</MenuItem>
                </Select>
              </FormControl>

              <TextField
                fullWidth
                label="主色调"
                value={localConfig.theme?.primary_color || '#1976d2'}
                onChange={(e) => updateLocalConfig({
                  theme: {
                    ...localConfig.theme,
                    primary_color: e.target.value
                  }
                })}
                sx={{ mb: 2 }}
              />

              <TextField
                fullWidth
                label="辅助色调"
                value={localConfig.theme?.secondary_color || '#dc004e'}
                onChange={(e) => updateLocalConfig({
                  theme: {
                    ...localConfig.theme,
                    secondary_color: e.target.value
                  }
                })}
              />
            </CardContent>
          </Card>
        </TabPanel>

        {/* 终端设置 */}
        <TabPanel value={currentTab} index={2}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                终端默认设置
              </Typography>
              
              <TextField
                fullWidth
                label="字体系列"
                value={localConfig.terminal_defaults?.font_family || 'SF Mono, Monaco, Consolas, monospace'}
                onChange={(e) => updateLocalConfig({
                  terminal_defaults: {
                    ...localConfig.terminal_defaults,
                    font_family: e.target.value
                  }
                })}
                sx={{ mb: 2 }}
              />

              <Box sx={{ mb: 2 }}>
                <Typography gutterBottom>
                  字体大小: {localConfig.terminal_defaults?.font_size || 14}px
                </Typography>
                <Slider
                  value={localConfig.terminal_defaults?.font_size || 14}
                  onChange={(_, value) => updateLocalConfig({
                    terminal_defaults: {
                      ...localConfig.terminal_defaults,
                      font_size: value as number
                    }
                  })}
                  min={8}
                  max={24}
                  step={1}
                  marks
                  valueLabelDisplay="auto"
                />
              </Box>

              <FormControl fullWidth sx={{ mb: 2 }}>
                <InputLabel>光标样式</InputLabel>
                <Select
                  value={localConfig.terminal_defaults?.cursor_style || 'block'}
                  label="光标样式"
                  onChange={(e) => updateLocalConfig({
                    terminal_defaults: {
                      ...localConfig.terminal_defaults,
                      cursor_style: e.target.value as any
                    }
                  })}
                >
                  <MenuItem value="block">块状</MenuItem>
                  <MenuItem value="underline">下划线</MenuItem>
                  <MenuItem value="bar">竖线</MenuItem>
                </Select>
              </FormControl>

              <FormControlLabel
                control={
                  <Switch
                    checked={localConfig.terminal_defaults?.cursor_blink || false}
                    onChange={(e) => updateLocalConfig({
                      terminal_defaults: {
                        ...localConfig.terminal_defaults,
                        cursor_blink: e.target.checked
                      }
                    })}
                  />
                }
                label="光标闪烁"
                sx={{ mb: 2 }}
              />

              <TextField
                fullWidth
                label="滚动缓冲区大小"
                type="number"
                value={localConfig.terminal_defaults?.scrollback || 10000}
                onChange={(e) => updateLocalConfig({
                  terminal_defaults: {
                    ...localConfig.terminal_defaults,
                    scrollback: parseInt(e.target.value) || 10000
                  }
                })}
                sx={{ mb: 2 }}
              />

              <FormControlLabel
                control={
                  <Switch
                    checked={localConfig.terminal_defaults?.bell_sound || false}
                    onChange={(e) => updateLocalConfig({
                      terminal_defaults: {
                        ...localConfig.terminal_defaults,
                        bell_sound: e.target.checked
                      }
                    })}
                  />
                }
                label="响铃声音"
              />
            </CardContent>
          </Card>
        </TabPanel>

        {/* 安全设置 */}
        <TabPanel value={currentTab} index={3}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    安全配置
                  </Typography>
                  
                  <FormControlLabel
                    control={
                      <Switch
                        checked={localConfig.security?.encrypt_passwords || true}
                        onChange={(e) => updateLocalConfig({
                          security: {
                            ...localConfig.security,
                            encrypt_passwords: e.target.checked
                          }
                        })}
                      />
                    }
                    label="加密存储密码"
                    sx={{ mb: 2 }}
                  />

                  <FormControlLabel
                    control={
                      <Switch
                        checked={localConfig.security?.auto_lock || false}
                        onChange={(e) => updateLocalConfig({
                          security: {
                            ...localConfig.security,
                            auto_lock: e.target.checked
                          }
                        })}
                      />
                    }
                    label="自动锁定"
                    sx={{ mb: 2 }}
                  />

                  {localConfig.security?.auto_lock && (
                    <TextField
                      fullWidth
                      label="自动锁定时间（分钟）"
                      type="number"
                      value={localConfig.security?.lock_timeout_minutes || 30}
                      onChange={(e) => updateLocalConfig({
                        security: {
                          ...localConfig.security,
                          lock_timeout_minutes: parseInt(e.target.value) || 30
                        }
                      })}
                      sx={{ mb: 2 }}
                    />
                  )}

                  <FormControlLabel
                    control={
                      <Switch
                        checked={localConfig.security?.clear_clipboard || false}
                        onChange={(e) => updateLocalConfig({
                          security: {
                            ...localConfig.security,
                            clear_clipboard: e.target.checked
                          }
                        })}
                      />
                    }
                    label="自动清除剪贴板"
                  />
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </TabPanel>

        {/* 关于 */}
        <TabPanel value={currentTab} index={4}>
          <Card>
            <CardContent>
              <Typography variant="h4" gutterBottom>
                Tabby Desktop
              </Typography>
              
              <Typography variant="body1" color="text.secondary" paragraph>
                基于 Rust 和 Tauri 构建的现代化 SSH 客户端
              </Typography>

              <Box sx={{ mb: 3 }}>
                <Chip label={`版本 ${localConfig.app_version}`} color="primary" sx={{ mr: 1 }} />
                <Chip label="Rust + Tauri" variant="outlined" sx={{ mr: 1 }} />
                <Chip label="React + TypeScript" variant="outlined" />
              </Box>

              <Divider sx={{ my: 2 }} />

              <Typography variant="h6" gutterBottom>
                功能特性
              </Typography>
              
              <List dense>
                <ListItem>
                  <ListItemText primary="SSH 连接管理" secondary="支持密码和密钥认证" />
                </ListItem>
                <ListItem>
                  <ListItemText primary="终端模拟器" secondary="基于 Xterm.js 的现代终端" />
                </ListItem>
                <ListItem>
                  <ListItemText primary="SSH 隧道" secondary="本地和远程端口转发" />
                </ListItem>
                <ListItem>
                  <ListItemText primary="安全存储" secondary="加密保存敏感信息" />
                </ListItem>
                <ListItem>
                  <ListItemText primary="主题定制" secondary="支持浅色和深色主题" />
                </ListItem>
              </List>
            </CardContent>
          </Card>
        </TabPanel>
      </Box>

      {/* 重置确认对话框 */}
      <Dialog
        open={showResetDialog}
        onClose={() => setShowResetDialog(false)}
      >
        <DialogTitle>重置配置</DialogTitle>
        <DialogContent>
          <Typography>
            确定要将所有设置重置为默认值吗？此操作无法撤销。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowResetDialog(false)}>取消</Button>
          <Button onClick={resetConfig} color="error" disabled={isLoading}>
            重置
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Settings;